# -*- coding:utf-8 -*-
import os
import configparser
import requests
import json
import logging
import sys


class Config():
    '''
    解析配置文件
    '''
    def __init__(self):
        pass

    @staticmethod
    def GetConfig(environment = "Beta"):
        '''
        :param environment: 选择对应环境 Pro=线上 Beta=Beta Dev=Dev
        :returns: HeyuAPPDomians:域名地址
        :returns: HeyuWebDomains:域名地址
        :returns: CommontParams:返回公共参数 app p
        :returns: Driver1 Driver2:两位司机的手机号码
        '''
        cf = configparser.ConfigParser()
        path = os.path.dirname(os.path.abspath(__file__))
        cf.read(filenames=path+"/Commonconfig.ini",encoding="utf8")
        HeyuAPPDomains = cf.get(section=environment,option='HeyuAPP')
        HeyuWebDomains = cf.get(section=environment,option="HeyuWeb")
        App = cf.get(section="CommonParams",option="app")
        P ={}
        P['version'] = cf.get(section="CommonParams",option="version")
        P['readableVersion'] = cf.get(section="CommonParams", option="readableVersion")
        P['platform'] = cf.get(section="CommonParams", option="platform")
        P['os'] = cf.get(section="CommonParams", option="os")
        P['uniqueId'] = cf.get(section="CommonParams", option="uniqueId")
        P['build'] = cf.get(section="CommonParams", option="build")
        P['cid'] = cf.get(section="CommonParams", option="cid")
        P['curLocation'] = cf.get(section="CommonParams", option="curLocation")
        P['curCity'] = cf.get(section="CommonParams", option="curCity")
        Driver1 = cf.get(section="Driver",option="Driver1")
        Driver2 = cf.get(section="Driver",option="Driver2")
        srcLocation = cf.get(section="CommonParams",option="srcLocation")
        destLocation = cf.get(section="CommonParams",option="destLocation")
        contactList = cf.get(section="CommonParams",option="contactList")
        User1ShuntKey = cf.get(section=environment,option="User1ShuntKey")
        User2ShuntKey = cf.get(section=environment,option="User2ShuntKey")
        return HeyuAPPDomains,HeyuWebDomains,App,P,Driver1,Driver2,srcLocation,destLocation,contactList,User1ShuntKey,User2ShuntKey





class SassHeyuAPP(Config):
    '''
    和御出行业务接口校验
    '''

    def __init__(self):
        self.AppUrl = Config.GetConfig()[0]
        self.WebUrl = Config.GetConfig()[1]
        self.App = Config.GetConfig()[2]
        self.P = Config.GetConfig()[3]
        self.Driver1 = Config.GetConfig()[4]
        self.Driver2 = Config.GetConfig()[5]
        self.srcLocation = Config.GetConfig()[6]
        self.destLocation = Config.GetConfig()[7]
        self.contactList = Config.GetConfig()[8]
        self.User1ShuntKey = Config.GetConfig()[9]
        self.User2ShuntKey = Config.GetConfig()[10]

    #登录获取用户的cookie
    def Cookie(self,User):
        '''
        :param User:用户 0 = Driver1 1 = Driver2
        :return: CookieValue
        '''
        if User ==0:
            Phone = self.Driver1
            ShuntKey = self.User1ShuntKey
        else:
            Phone = self.Driver2
            ShuntKey = self.User2ShuntKey
        Url = self.AppUrl+'/webapi/app/user/login/phone'
        Params = {"app":self.App,"p":self.P,"phone":Phone,"authcode":"0000","uuid":"ac66fb76-9b71-497f-af03-a48a6492d957"}
        Response = requests.post(url=Url,json=Params)
        Cookies = Response.cookies.get_dict()
        for k in Cookies:
            Key = k
            Value = Cookies[k]
        CookieValue = Key+"="+Value+";"+ShuntKey
        print(CookieValue)
        return CookieValue



    #销毁订单
    def DestroyOrder(self,User):
        '''

        :param User: 需要销毁订单的司机 0 or 1
        :return: None
        '''
        CurrentOrder = self.OrderCheck(User=User)
        Headers = {"Cookie": self.Cookie(User=User)}
        if len(CurrentOrder) !=0:
            for i in CurrentOrder:
                OrderNo = i
            if CurrentOrder[OrderNo] == "Submit":
                Url = self.AppUrl+"/webapi/app/order/action/finish"
                Params = {"orderNo":OrderNo,"app":self.App,"p":self.P,"factDistance":"0"}
                Resp = requests.post(url=Url,json=Params,headers=Headers).content.decode()
                #feeSubmit
                UrlFee = self.AppUrl+"/webapi/app/order/fee/confirm/submit"
                ParamsFee = {"orderNo":OrderNo,"app":self.App,"p":self.P,"priceAgree":"30"}
                RespFee = requests.post(url=UrlFee,json=ParamsFee,headers=Headers).content.decode()
                #clollect offline
                UrlCollect = self.AppUrl+"/webapi/app/order/collect/offline"
                ParamsCollect = {"orderNo":OrderNo,"app":self.App,"p":self.P,"priceTotal":"30"}
                RespCollect = requests.post(url=UrlCollect,json=ParamsCollect,headers=Headers).content.decode()
                logging.info(sys._getframe(0).f_code.co_name+" 完成收费上报 "+RespCollect)
            elif CurrentOrder[OrderNo] == "Deliver":
                Url =self.AppUrl+"/webapi/app/order/accept/cancel"
                ParamsCancel = {"orderNo":OrderNo,"app":self.App,"p":self.P,"reason":"测试机器人取消"}
                RespCancle = requests.post(url=Url,json=ParamsCancel,headers=Headers).content.decode()
                logging.info(sys._getframe(0).f_code.co_name+"已取消当前接单！"+RespCancle)

            else:
                logging.info(sys._getframe(0).f_code.co_name+"其他未知类型的订单！")

        else:
            logging.info(sys._getframe(0).f_code.co_name + "当前没有需要销毁的订单！")
    #检查当前订单状态
    def OrderCheck(self,User):
        '''
        :param User:需要查询订单状态的司机 0 or 1
        :return:OrderNo
        '''
        headers = {"Cookie":self.Cookie(User=User)}
        url  = self.AppUrl+"/webapi/app/order/info/current"
        OrderDetail = {}
        resp = requests.post(url=url,headers=headers).content.decode()
        result = json.loads(resp)['result']
        if len(result) == 0 :
            logging.info(sys._getframe(0).f_code.co_name+"当前无进行中的订单")
        else:
            OrderNo = json.loads(resp)['result']['orderNo']
            if resp.__contains__("deliverInfo"):
                OrderDetail[OrderNo] = "Deliver"
            else:
                OrderDetail[OrderNo] = "Submit"
        return OrderDetail



    #创建报单
    def MakeSubmitOrder(self,User=0):
        '''
        :param User: 创建报单的司机 0 or 1
        :return: orderNo  创建报单的订单号
        '''
        #先从init接口获取orderNo
        headers = {"Cookie":self.Cookie(User=User)}
        data = {"app":self.App,"p":self.P,"srcLocation":self.srcLocation,"destLocation":self.destLocation}
        url = self.AppUrl+"/webapi/app/order/info/init"
        resp = requests.post(url=url,json=data,headers=headers)
        self.DestroyOrder(User=User)
        if resp.status_code == 200:
            orderNo = json.loads(resp.content.decode())['result']['orderNo']
            #根据生成的订单号提交订单
            data['needContactPhone'] = "0"
            data['orderNo'] = orderNo
            data['insure'] = "1"
            data['orderType'] = "1"
            data['contactPhone'] = '18571015163'
            resp = requests.post(url=self.AppUrl+"/webapi/app/order/info/submitstart",json=data,headers=headers)
            if resp.status_code == 200:
                print("创建订单成功！")
                logging.info("创建报单成功！"+resp.content.decode())
            else:
                logging.warning(sys._getframe(0).f_code.co_name+'创建订单失败'+resp.content.decode())
        else:
            orderNo = None
            logging.warning(sys._getframe(0).f_code.co_name+"接口请求异常")
        return orderNo


    #创建派单
    def MakeSendOrder(self,User):
        '''

        :param User: 创建派单的司机 0 or 1
        :return: OrderNo 订单号
        '''
        self.DestroyOrder(User=0)
        self.DestroyOrder(User=1)
        cookies = self.Cookie(User=User)
        url = self.AppUrl + "/webapi/app/order/deliver/submit"
        headers = {"Cookie": cookies}
        data = {}
        data['contactPhone'] = "18571015163"
        data['app'] = self.App
        data['p'] = self.P
        data['destLocation'] = self.destLocation
        data['srcLocation'] = self.srcLocation
        data['confirmInfo'] = "1"
        try:
            Resp = requests.post(url=url, json=data, headers=headers)
            OrderNo = json.loads(Resp.content.decode())['result']['orderNo']
            logging.info(sys._getframe(0).f_code.co_name+" 已派单，派单号： "+OrderNo)
        except:
            OrderNo = None
            logging.warning(sys._getframe(0).f_code.co_name+"派单出现异常！")
        return OrderNo


    #司机接单
    def AcceptOrder(self,User1=0,User2=1):
        '''
        User1和User2是两个人不同的司机
        :param User1: 派单司机 0 or 1
        :param User2: 接单司机 0 or 1
        :return:AcceptOrderNo
        '''
        orderNo = self.MakeSendOrder(User=User1)
        logging.warning(sys._getframe(0).f_code.co_name+orderNo)
        headers = {"Cookie":self.Cookie(User=User2)}
        url = self.AppUrl+"/webapi/app/order/accept/apply"
        params = {"sence":"socket push","app":self.App,"p":self.P,"orderNo":orderNo,"reason":"accept"}
        print(url,params,headers)
        resp = requests.post(url=url,json=params,headers=headers).content.decode()
        logging.warning(resp)
        # status = int(json.loads(resp)['status'])
        try:
            AcceptOrderNo = json.loads(resp)['result']['orderNo']
            logging.info(sys._getframe(0).f_code.co_name + " 抢单成功！")
            print(sys._getframe(0).f_code.co_name + " " + resp)
        except:
            AcceptOrderNo = None
            logging.warning(sys._getframe(0).f_code.co_name+"抢单失败！")

        # if status ==1:
        #     print(sys._getframe(0).f_code.co_name+" " +resp)
        #     logging.info(sys._getframe(0).f_code.co_name+"抢单成功！")
        #     AcceptOrderNo = json.loads(resp)['result']['orderNo']
        #
        # else:
        #     AcceptOrderNo = None
        #     logging.warning(sys._getframe(0).f_code.co_name+"抢单失败！")
        return AcceptOrderNo



    def OrderReady(self,User1,User2):
        '''
        :param  User1
        :param  User2
        :return:OrderNo
        '''
        AccepOrderNo = self.AcceptOrder(User1=User1,User2=User2)
        logging.warning('拿到订单号了'+str(AccepOrderNo))
        Headers = {"Cookie":self.Cookie(User2)}
        logging.warning("拿到请求头了")
        Params = {"orderNo":AccepOrderNo,"app":self.App,"p":self.P}
        logging.warning("完成参数设置了")
        Url = self.AppUrl+"/webapi/app/order/action/ready"
        logging.warning("完成URL设置了")
        Resp = requests.post(url=Url,json=Params,headers=Headers).content.decode()
        logging.warning("开始请求了")
        print(Resp)
        logging.info(sys._getframe(0).f_code.co_name+Resp)
        logging.warning(Resp)
        OrderNo = json.loads(Resp)['result']['orderNo']
        return OrderNo

    def RequestJson(self,**kwargs):
        '''

        :param kwargs:
        :return: jsons
        '''
        jsons = {}
        if kwargs:
            jsons['app'] = self.App
            jsons['p'] = self.P
            jsons.update(kwargs)
            return json.dumps(jsons,ensure_ascii=True)
        else:
            jsons['app'] = self.App
            jsons['p'] = self.P
            return json.dumps(jsons,ensure_ascii=False)


    #自定义请求参数
    @staticmethod
    def DiyJson(**kwargs):
        '''
        :param kwargs:
        :return: jsons
        '''
        jsons = {}
        if kwargs:
            jsons.update(kwargs)
            logging.info(sys._getframe(0).f_code.co_name+json.dumps(jsons))
            return json.dumps(jsons, ensure_ascii=False)
        else:
            pass


    def WriteParams(self,**kwargs:dict):
        Variables = {}
        path = os.path.dirname(os.path.abspath(__file__))
        Variables['${domains}'] = self.AppUrl
        Variables['${srcLocation}'] = self.srcLocation
        Variables['${contactList} '] = self.contactList
        Variables['${destLocation}'] = self.destLocation
        with open(path + '/Variables/params.txt', 'w', encoding='utf-8') as f:
            f.truncate()
            f.writelines("*** Variables ***\n")
            for i in Variables.keys():
                    str = i+"    "+Variables[i]
                    print(str)
                    f.writelines(i+"    "+Variables[i])
                    f.writelines('\n')


    def test(self):
        print(self.AppUrl)
        print(self.P)
        print(self.Driver2)
        print(self.Cookie(User=0))
        print(os.path.dirname(os.path.abspath(__file__))+"/Variables/params.txt")


if __name__ == '__main__':
    pass
